package mdw

import (
	"context"
	"fmt"
	"time"
)

//可参考：https://gowebexamples.com/advanced-middleware/

type MiddlewareFunc func(ctx context.Context, request interface{}) (response interface{}, err error)

type Middleware func(MiddlewareFunc) MiddlewareFunc

type LogFile struct {
	logName string
}

//执行时间
func ExeTime(next MiddlewareFunc) MiddlewareFunc {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		fmt.Println("执行时间中间件")
		startTime := time.Now().UnixNano()
		response, err = next(ctx, request)
		if err != nil {
			fmt.Println("执行函数失败")
			return
		}
		endTime := time.Now().UnixNano()
		fmt.Println("函数执行时间为:", endTime-startTime)
		return
	}
}

//打印日志
func NewPrintLog(LogFiler LogFile) Middleware {
	return func(next MiddlewareFunc) MiddlewareFunc {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {
			fmt.Println("打印日志中间件")
			fmt.Println(LogFiler.logName)
			response, err = next(ctx, request)
			return
		}
	}
}

//判断请求
func judgeReq(next MiddlewareFunc) MiddlewareFunc {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		fmt.Println("判断req是否为空中间件")
		if request == "" {
			fmt.Println("req为空")
			return
		}
		response, err = next(ctx, request)
		return
	}
}

//处理
func Handle(ctx context.Context, request interface{}) (response interface{}, err error) {
	response = request
	fmt.Println("Handle")
	time.Sleep(time.Second)
	return
}

//构建调用链
func buildChain(chain []Middleware) Middleware {
	return func(next MiddlewareFunc) MiddlewareFunc {
		for i := len(chain) - 1; i >= 0; i-- {
			next = chain[i](next)
		}
		return next
	}
}

//构建中间件
func buildMiddleWare(handle MiddlewareFunc) MiddlewareFunc {
	var chain []Middleware
	var LogFiler LogFile
	chain = append(chain, ExeTime)
	chain = append(chain, NewPrintLog(LogFiler))
	chain = append(chain, judgeReq)

	middle := buildChain(chain)
	return middle(handle)
}
